// import BASE_URL from '@/api/env.js' //引入接口共用地址
import RequestManager from './requestManager.js'
import {
	toast,
	clearStorageSync,
	getStorageSync,
	useRouter
} from '@/utils/utils.js'
import systemConfig from '@/config/config.js';
const manager = new RequestManager()

import axios from 'axios'

import settle from 'axios/lib/core/settle'
import buildURL from 'axios/lib/helpers/buildURL'
import buildFullPath from 'axios/lib/core/buildFullPath'
import envParams from '@/api/env.js'

axios.defaults.adapter = function(config) {
	console.log('adapter config', config)
	return new Promise((resolve, reject) => {
		let fullurl = buildFullPath(config.baseURL, config.url)
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(fullurl, config.params, config.paramsSerializer),
			header: Object.assign({}, config.headers || {}),
			data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: (response) => {
				let responseC = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, responseC);
			}
		})
	})
}

let instance;


// #ifdef MP
instance = axios.create({
	baseURL: envParams.BASE_URL,
	timeout: 60 * 1000,
	withCredentials: true,
	crossDomain: true
})
// #endif

// #ifndef MP
instance = axios.create({
	baseURL: envParams.BASE_URL,
	timeout: 60 * 1000,
	withCredentials: true,
	crossDomain: true,
	responseType: 'json'
})
// #endif

instance.interceptors.request.use(async config => {
	config.headers.Authorization = getStorageSync(systemConfig.token) || ''
	console.log('interceptors config', config)
	return config
}, error => {
	console.log('err' + error)
	let {
		message
	} = error
	if (message == 'Network Error') {
		message = '后端接口连接异常'
	} else if (message.includes('timeout')) {
		message = '系统接口请求超时'
	} else if (message.includes('Request failed with status code')) {
		message = '系统接口' + message.substr(message.length - 3) + '异常'
	}
	uni.showModal({
		title: '提示',
		content: message,
		success: function(res) {
			if (res.confirm) {
				console.log('用户点击确定');
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
	return Promise.reject(error)
})


instance.interceptors.response.use(response => {
	console.log('response', response)
	if (response.status >= 200 && response.status < 300) {
		return response.data
	} else {
		return {
			status: response.status,
			msg: 'err'
		}
	}
}, error => {
	//token过期 重新登陆
	console.log('error', error)
	if (error.response?.status == 401) {
		toast('当前登录已过期，请重新登录！')
		setTimeout(function() {
			uni.reLaunch({
				url: systemConfig.login_page
			})
		}, 500)
	} else if (error.response?.status == 403) {
		toast('您的账号在另一台设备上登录，如非本人操作，请立即修改密码！')
		setTimeout(function() {
			uni.reLaunch({
				url: systemConfig.login_page
			})
		}, 500)
	}
	return Promise.reject(error)
})

export default instance